$package("common.config.userCustom");
$import('common.knowledge.knowledgeDetail');
$import("common.jbpm.processTask"); 
/**  
 * @author Van  
 * @constructor updateLevelMain
 * @description  门户面板数据加载主函数
 * @date 2010-11-17
 * @since version 1.0 
 */  
common.config.userCustom.dashboardDataLoad=function(){
	return{
		/**
		 * 加载面板数据
		 */
		loadDashboardData:function(){
			startProcess();
			$.post('view!findAllT_View.action','queryDTO.userName='+userName+'&&queryDTO.customType=1',function(rdata){
				if(rdata !== null && rdata.viewdtos != null){
					var count=0;
					for(var i=0;i<rdata.viewdtos.length;i++){
						var viewContent = rdata.viewdtos[i].viewContent;
						//console.info(viewContent);
						var tableID=rdata.viewdtos[i].viewId;
						if(rdata.viewdtos[i].viewType=='filterView'){  //过滤器视图
							var filterID=parseFloat(viewContent);
							common.config.userCustom.dashboardDataLoad.findFilter(tableID,filterID);
						}else if(rdata.viewdtos[i].viewType=='staticView'){   //静态视图
							common.config.userCustom.dashboardDataLoad.loadStaticView(tableID,viewContent);
						}else if(rdata.viewdtos[i].viewType=='singleView'){   //报表视图
							common.config.userCustom.dashboardDataLoad.showReport('singleReportView',viewContent,tableID);
						}else if(rdata.viewdtos[i].viewType=='mutilsView'){
							common.config.userCustom.dashboardDataLoad.showReport('mutilReportView',viewContent,tableID);
						}else if(rdata.viewdtos[i].viewType=='KPIREPView'){
							common.config.userCustom.dashboardDataLoad.showReport('KPIReportView',viewContent,tableID);
						}else{ //crossReportView
							common.config.userCustom.dashboardDataLoad.showReport('crossReportView',viewContent,tableID);
						}
						count++;
					}
					if(rdata.customType == 0 && rdata.viewdtos.length == count ){
						common.config.userCustom.dashboardDataLoad.saveLayout();
					}
				}
				endProcess();
			});
		},
		/**
		 * 加载配置项面板
		 * @param tabId 面板TableID
		 */
		loadCiView:function(tabId){//onkeyup="this.value=this.value.replace(/\D/g,'')" onkeyup="this.value=this.value.replace(/\D/g,'')"
			setTimeout(function(){
				var widths=$(tabId).width();
				widths=widths-10;
				$(tabId).append('<tr><td><input type="hidden" id="CiSelectId" value="'+tabId+'">'+i18n['lable_ci_assetNo']+':<input style="width:100%"	 type="text" id="selectCINo">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr></tr><td>'+i18n['configureitem']+i18n['title_snmp_IP']+':<input style="width:100%" type="text" id="selectCIIp">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a id="searchCIBtn" onclick="common.config.userCustom.dashboardDataLoad.selectCIView()" class="easyui-linkbutton l-btn l-btn-plain" icon="icon-search" plain="true"><span class="l-btn-left"><span class="l-btn-text icon-search" style="padding-left: 20px;">'+i18n['search']+'</span></span></a></td></tr>');
			},10);
		},
		/**
		 * 显示报表面板
		 * @param reportType 报表类型
		 * @param tableId  面板TableID
		 * @param viewContent 显示内容
		 * @param divId 面板DIVID
		 */
		showReport:function(reportType,viewContent,divId){
			viewContent = parseFloat(viewContent);
			var url = '';
			if(reportType=='singleReportView'){
				url = 'sgreport!showdynamic.action?reportId='+viewContent+'&width=560';
			}else if(reportType=='mutilReportView'){
				url = 'mutilreport!showdynamic.action?reportId='+viewContent+'&width=560';
			}else if(reportType=='KPIReportView'){
				url = 'kpireport!showdynamic.action?reportId='+viewContent+'&width=560';
			}else{
				url = 'crossreport!showdreport.action?reportId='+viewContent;
			}
			startProcess();
			$.post(url,function(data){
				endProcess();
				$("#TAB_ID_"+divId).html(data);
			});
			var view=document.getElementById("protlet_content_"+divId);//设置报表div高度，超过就添加滚动条 
			view.style.maxHeight = "400px";
			view.style.overflow="auto";
			var tab=document.getElementById("TAB_ID_"+divId);//页面加载后，头部出现的空白头部 
			tab.style.marginTop = "-10px";
		},
		/**
		 * 显示静态面板
		 * @param tableId  面板TableID
		 * @param viewContent 显示内容
		 */
		loadStaticView:function(tableID,viewContent){
			switch(viewContent){
				case 'view_newKnowledge':
					common.knowledge.leftMenu.showKnowledgePortal('#TAB_ID_'+tableID,'NewKnowledge');
					break;
				case 'view_hotKnowledge':
					common.knowledge.leftMenu.showKnowledgePortal('#TAB_ID_'+tableID,'PopularKnowledge');
					break;
				case 'view_myTask':
					showMyTask('#TAB_ID_'+tableID);
					break;
				case 'view_instantMessage':
					showMyIM('#TAB_ID_'+tableID);
					break;
				case 'view_affche':
					showAffiche('#TAB_ID_'+tableID);
					break;
				case 'view_myProcessingTasks'://我待处理的任务
					common.jbpm.processTask.showMyProcessingTasksDashboard(tableID);
					portalGridID[portalGridID.length]=tableID;
					break;
				case 'view_tasksAssignedToOurTeam'://指派给我组的任务
					common.jbpm.processTask.showTasksAssignedToOurTeamDashboard(tableID);
					portalGridID[portalGridID.length]=tableID;
					break;	
				case 'view_flowTaskStat'://任务统计
					common.jbpm.processTask.taskStat(tableID);
					break;
				case 'view_requestTaskStat'://请求统计
					common.config.userCustom.dashboardDataLoad.requestStats(tableID);
					break;
				case 'view_LoginQuickCall'://快速创建请求
					common.config.userCustom.dashboardDataLoad.loadLoginQuickCallView(tableID);
					break;
				case 'CIID'://配置项检索
					common.config.userCustom.dashboardDataLoad.loadCiView('#TAB_ID_'+tableID);
					break;
				case 'view_assignToMeRequest'://指派给我的请求
					common.config.userCustom.dashboardDataLoad.assignToMeRequest(tableID);
					portalGridID[portalGridID.length]=tableID;
					break;
			}
		},
		requestStats:function(tableID){
			$('#TAB_ID_'+tableID).html($('#requestStatsLeftDiv').html());
			var url = 'request!countRequest.action';
			$.post(url,'requestQueryDTO.loginName='+userName+'&requestQueryDTO.currentUser='+userName,function(res){
				$("#view_allRequest").text("[ "+res.countAllRquest+" ]");
				
				$("#view_myProposedRequest").text("[ "+res.countMyRquest+" ]");
				$("#view_myGroupProposedRequest").text("[ "+res.countMyGroupProposedRequest+" ]");
				
				$("#view_assigneeToMyRequest").text("[ "+res.countMyPeRquest+" ]");
				$("#view_assigneeGroupRequest").text("[ "+res.countMyGrRquest+" ]");
				
				$("#view_myOwnerRequest").text("[ "+res.countMyOwRquest+" ]");
				$("#view_myNotComprehensiveNotSubmitted").text("[ "+res.myNotComprehensiveNotSubmittedRequest+" ]");
				$("#view_actingToMyRequest").text("[ "+res.countactingToMyRequest+" ]");
			});
		},
		/**
		 * @description 请求统计搜索
		 * @param type 统计类型
		 */
		requestCountSearch:function(type){
			basics.tab.tabUtils.refreshTab(i18n.title_request_requestGrid,"../pages/itsm/request/requestMain.jsp?countQueryType="+type);
		},
		assignToMeRequest:function(tableID){
			var requestUrl='request!findRequests.action?requestQueryDTO.assigneeName='+userName;
			var params = $.extend({},jqGridParams,{
				caption:'',
				url:requestUrl,
				colNames:['ID',i18n['number'],i18n['common_title'],i18n['category'],i18n['common_state'],i18n['common_createTime'],i18n['requester']],
				colModel:[
				          {name:'eno',hidden:true},
				          {name:'requestCode'},
                          {name:'etitle'},
                          {name:'requestCategoryName',index:'requestCategory',align:'center',hidden:false},
                          {name:'statusName',index:'status',align:'center',hidden:false,formatter:function(cellvalue, options, rowObject){
                        	  return colorFormatter(rowObject.statusColor,cellvalue);
 						  }},
 						 {name:'createdOn',formatter:timeFormatter,align:'center',hidden:false},
 						 {name:'createdByName',index:'createdBy',align:'center',hidden:false},
                          ],
                  toolbar:false,
                  multiselect:false,
                  jsonReader: $.extend(jqGridJsonReader, {id: "eno"}),
                  sortname:'eno',
                  ondblClickRow:function(rowId){basics.tab.tabUtils.reOpenTab("request!requestDetails.action?eno="+rowId,i18n["request_detail"]);},
                  pager:'#'+tableID+'_0',
                  gridComplete:function(){
                	  portalScrollRefresh();
                  }
			});
			$("#TAB_ID_"+tableID).jqGrid(params);
			$("#TAB_ID_"+tableID).navGrid('#'+tableID+'_0',navGridParams);
		},
		/**
		 * 加载快速创建请求
		 * @param tabId 面板TableID
		 */
		loadLoginQuickCallView:function(tabId){
			setTimeout(function(){
				$("#protlet_content_"+tabId).html($("#LoginQuickCall_view").html());
				//初始化请求内容描述富文本
				setTimeout(function(){
					initCkeditor('fastCreateEdesc_view','Simple',function(){});
				},0);
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('effectRange','#fastRequest_effectRange_view');
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('seriousness','#fastRequest_seriousness_view');
				common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('priority','#fastRequest_priority_view');
			},0);
		},
		/**
		 * 显示过滤器面板
		 * @param tableId  面板TableID
		 * @param filterID 过滤器Id
		 */
		findFilter:function(tableID,filterID){
			var filterUrl="filter!findFilterById.action?queryDTO.filterId="+filterID;
			$.post(filterUrl,function(fdata){
				//first,if fliterID eq filterId,don't do if;
				//if filterID not eq filterId, Filter is delete,we first must delete view make filterID and update view String.
				if(filterID!==fdata.filterId){
					$("#protlet_"+tableID).remove();
					common.config.userCustom.dashboardDataLoad.saveLayout();
				}
				if(fdata.filterCategory=='request'){
					var requestUrl='request!findPagerRequestByCustomFilter.action?requestQueryDTO.filterId='+filterID;
					var params = $.extend({},jqGridParams,{
						caption:'',
						url:requestUrl,
						colNames:['ID',i18n['number'],i18n['common_title'],i18n['category'],i18n['common_state'],i18n['common_createTime'],i18n['requester']],
						colModel:[
						          {name:'eno',hidden:true},
						          {name:'requestCode'},
                                  {name:'etitle'},
                                  {name:'requestCategoryName',index:'requestCategory',align:'center',hidden:false},
                                  {name:'statusName',index:'status',align:'center',hidden:false,formatter:function(cellvalue, options, rowObject){
                                	  return colorFormatter(rowObject.statusColor,cellvalue);
         						  }},
         						 {name:'createdOn',formatter:timeFormatter,align:'center',hidden:false},
         						 {name:'createdByName',index:'createdBy',align:'center',hidden:false},
                                  ],
                          toolbar:false,
                          multiselect:false,
                          jsonReader: $.extend(jqGridJsonReader, {id: "eno"}),
                          sortname:'eno',
	                      ondblClickRow:function(rowId){basics.tab.tabUtils.reOpenTab("request!requestDetails.action?eno="+rowId,i18n["request_detail"]);},
	                      pager:'#'+tableID+'_0',
	                      gridComplete:function(){
	                    	  portalScrollRefresh();
	                      }
					});
					$("#TAB_ID_"+tableID).jqGrid(params);
					$("#TAB_ID_"+tableID).navGrid('#'+tableID+'_0',navGridParams);
				}else if(fdata.filterCategory=='change'){
					var changeUrl="change!findPagerChangeByCustomFilter.action?queryDTO.filterId="+filterID;
					var params = $.extend({},jqGridParams,{
							caption:'',
							url:changeUrl,
							colNames:['ID',i18n['number'],i18n['title'],i18n['category'],i18n['status'],i18n['common_createTime'],i18n['title_creator']],
							colModel:[
							          {name:'eno',hidden:true},
							          {name:'changeNo'},
							          {name:'etitle'},
							          {name:'categoryName',index:'category'},
							          {name:'statusName',index:'status',formatter:function(cellvalue, options, rowObject){
											 return colorFormatter(rowObject.statusColor,cellvalue);
									    }},
									  {name:'createTime',index:'createdOn',formatter:timeFormatter},
									  {name:'creator',align:'center',index:'createdBy'},
                                      ],
	                        toolbar:false,
	                        multiselect:false,
                            jsonReader:$.extend(jqGridJsonReader,{id:'eno'}),
                            sortname:'eno',
                            ondblClickRow:function(rowId){basics.tab.tabUtils.reOpenTab('change!changeInfo.action?queryDTO.eno='+rowId,i18n['change_detail']);},
                            pager:'#'+tableID+'_0',
                            gridComplete:function(){
                          	  portalScrollRefresh();
                            }
					});
					$("#TAB_ID_"+tableID).jqGrid(params);
					$("#TAB_ID_"+tableID).navGrid('#'+tableID+'_0',navGridParams);
				}else if(fdata.filterCategory=='problem'){
					var problemUrl='problem!findProblemPagerByCustomFilter.action?queryDTO.filterId='+filterID;
					var params = $.extend({},jqGridParams,{
						caption:'',
						url:problemUrl,
						colNames:['ID',i18n['problem_code'],i18n['title'],i18n['category'],i18n['status'],i18n['problem_reportTime'],i18n['problem_reporter']],
						colModel:[
						          {name:'eno',hidden:true},
						          {name:'problemNo'},
						          {name:'etitle'},
						          {name:'categoryName',index:'category',align:'center'},
						          {name:'statusName',index:'status',width:80,align:'center',formatter:function(cellvalue, options, rowObject){
			  							 return colorFormatter(rowObject.statusColor,cellvalue);
			 						   }},
	 						      {name:'createdOn',align:'center',formatter:timeFormatter},
	 						      {name:'createdByName',align:'center',index:'createdBy'},
						          ],
				        toolbar:false,
				        multiselect:false,
			            jsonReader:$.extend(jqGridJsonReader,{id:'eno'}),
			            sortname:'eno',
			            ondblClickRow:function(rowId){
		            		basics.tab.tabUtils.reOpenTab('problem!findProblemById.action?eno='+rowId,i18n['probelm_detail']);
		                },
			            pager:'#'+tableID+'_0',
	                    gridComplete:function(){
	                    	portalScrollRefresh();
	                    }
					});
					$("#TAB_ID_"+tableID).jqGrid(params);
					$("#TAB_ID_"+tableID).navGrid('#'+tableID+'_0',navGridParams);
				}else if(fdata.filterCategory=='knowledge'){
					//分类、标题、发布人、更新时间、状态
					var knowledgeUrl='knowledgeInfo!findKnowledgesPagerByCustomFilter.action?knowledgeQueryDto.filterId='+filterID;
					var params = $.extend({},jqGridParams,{
						caption:'',
						url:knowledgeUrl,
						colNames:[i18n['number'],i18n['knowledge_knowledgeCategory'],i18n['title'],i18n['title_creator'],i18n['common_updateTime'],i18n['status']],
						colModel:[
						          {name:'kid',hidden:true},
						          {name:'categoryName',align:'center',sortable: false},
						          {name:'title'},
						          {name:'creatorFullName',align: 'center'},
						          {name:'lastUpdateTime',align: 'center',formatter: timeFormatter},
						          {name:'knowledgeStatus',align:'center',formatter: common.config.userCustom.dashboardDataLoad.statusFormatter},
						          ],
			            toolbar:false,
				        multiselect:false,
			            jsonReader:$.extend(jqGridJsonReader,{id:'kid'}),
			            sortname:'kid',
			            ondblClickRow:function(rowId){common.knowledge.knowledgeDetail.showKnowledgeDetail(rowId);},
			            pager:'#'+tableID+'_0',
			            gridComplete:function(){
	                    	portalScrollRefresh();
	                    }
					});
					$("#TAB_ID_"+tableID).jqGrid(params);
					$("#TAB_ID_"+tableID).navGrid('#'+tableID+'_0',navGridParams);
				}else if(fdata.filterCategory=='ci'){
					//分类、资产编号、名称、所在位置、状态
					var ciUrl='ci!findCItemsByCustomFilter.action?ciQueryDTO.filterId='+filterID;
					var params = $.extend({},jqGridParams,{
						caption:'',
						url:ciUrl,
						colNames:['ID',i18n['category'],i18n['lable_ci_assetNo'],i18n['name'],i18n['brands'],i18n['location']],
						colModel:[
						          {name:'ciId',hidden:true},
						          {name:'categoryName',index:'category',align:'center'},
						          {name:'cino',formatter:common.config.userCustom.dashboardDataLoad.ciNoUrlFrm},
						          {name:'ciname',formatter:common.config.userCustom.dashboardDataLoad.ciNameUrlFrm},
						          {name:'loc',align:'center',formatter:function(cellvalue, options, rowObject){
			  							 return colorFormatter(rowObject.locColor,cellvalue);
								   }},
								   {name:'status',align:'center',formatter:function(cellvalue, options, rowObject){
			  							 return colorFormatter(rowObject.statusColor,cellvalue);
								   }},
						          ],
			            toolbar:false,
				        multiselect:false,
			            jsonReader:$.extend(jqGridJsonReader,{id:'ciId'}),
			            sortname:'ciId',
			            ondblClickRow:function(rowId){common.config.userCustom.dashboardDataLoad.configureItemInfo(rowId);},
			            pager:'#'+tableID+'_0',
			            gridComplete:function(){
	                    	portalScrollRefresh();
	                    }
					});
					$("#TAB_ID_"+tableID).jqGrid(params);
					$("#TAB_ID_"+tableID).navGrid('#'+tableID+'_0',navGridParams);
				}
				portalGridID[portalGridID.length]=tableID;
			});
		},
		ciNoUrlFrm:function(cellvalue, options, rowObject){
			return rowObject.cino;
		},
		/**@description 打开详细信息页面*/
		configureItemInfo:function(ciId){
			basics.tab.tabUtils.reOpenTab('ci!findByciId.action?categoryType='+_categoryType+'&ciEditId='+ciId,i18n['ci_configureItemInfo']);
		},
		/**
		 * 保存面板位置
		 */
		saveLayout:function(){
			var types=$("#rowsWid").val();
			var list = "";
			var list1="";
			var  laytou={'fourRow':4,'threeRow':3,'twoRow':2,'oneRow':1};
			for(var i=0;i<laytou[types];i++){
				$.each($("#column_"+(i+1)+" .portlet"),function(m){
					var id = $(this).attr('viewId');
					list +=  id+ ":";
					list1+=(i+1)+":";
				});
			}
			startProcess();
			var url='userCustom!updateUserCustomView.action';
			/*var param={'userCustomDTO.loginName':userName,
					'userCustomDTO.viewIdStr':list,'userCustomDTO.customType':1,'userCustomDTO.layoutType':types,
					'userCustomDTO.viewRowsStr':list1};*/
			var param='userCustomDTO.loginName='+userName+
					'&userCustomDTO.viewIdStr='+list+'&userCustomDTO.customType='+1+'&userCustomDTO.layoutType='+types+'&userCustomDTO.viewRowsStr='+list1;
			$.ajax({
				type:"POST",
				async:false,
				url:url,
				data:param,
				success:function(res){
					resizePortalGrid();//自适应宽度
					//common.config.userCustom.dashboardDataLoad.setGridWidth(list,list1);
					endProcess();
				}
			});
		},
		/**
		 * 拖拽过滤器后设置过滤器的宽度
		 * @param  viewIdStr 视图编号字符
		 * @param  viewRowsStr 视图行字符
		 */
		setGridWidth:function(viewIdStr,viewRowsStr){
			var _viewIdStr = viewIdStr.split(':');
			var _viewRowsStr = viewRowsStr.split(':');
			for(var i=0;i<_viewIdStr.length;i++){
				var viewId= _viewIdStr[i];
				if(viewId!=null && viewId!=''){
					var setWidth=$("#column_"+_viewRowsStr[i]+" .portlet-header").css("width");
					if(setWidth!='auto'&&setWidth!=undefined){
						setWidth=setWidth.replace('px','');
						if(basics.ie6.htmlIsNull('#TAB_ID_'+viewId)){
							
							$('#TAB_ID_'+viewId).setGridWidth(setWidth-8);
						}
					}
					
				}
			}
		},
		/**
		 * 根据文本框中数据跳转到配置项详情
		 */
		selectCIView:function(){
			var CINo=$("#selectCINo").val();
			var CIIP=$("#selectCIIp").val();
			var url="";
			if(CINo != null && CINo != '' && CIIP != null && CIIP != ''){
				url='ci!findByCieno.action?findCino='+CINo;
				$.post(url,function(data){
					if(data != null && data.length > 0){
						$("#NoValue").remove();
						basics.tab.tabUtils.reOpenTab(url,i18n['ci_configureItemInfo']);
					}else{
						url='ci!findByHardwareIp.action?hardwareIP='+CIIP;
						common.config.userCustom.dashboardDataLoad.returnFindValue(url);
					}
				});
			}else if(CINo != null && CINo != ''){
				url='ci!findByCieno.action?findCino='+CINo;//,i18n['ci_configureItemInfo']
				common.config.userCustom.dashboardDataLoad.returnFindValue(url);
			}else if(CIIP != null && CIIP != ''){
				url='ci!findByHardwareIp.action?hardwareIP='+CIIP;
				common.config.userCustom.dashboardDataLoad.returnFindValue(url);
			}else{
				var values=$("#NoValue").length;
				if(values == 0){
					var CiselectId=$("#CiSelectId").val();
					$(CiselectId).append("<tr id='NoValue'><td align='center'><br><font color='#999999'>"+i18n.lable_notFindCi+"...</font></td></tr>");
				}
			} 
		},
		/**
		 * 根据Url查询返回值跳转到配置项详情
		 * @param URL 地址
		 * @private 
		 */
		returnFindValue:function(url){
			$.post(url,function(data){
				if(data != null && data.length > 0){
					$("#NoValue").remove();
					basics.tab.tabUtils.reOpenTab(url,i18n['ci_configureItemInfo']);
				}else{
					var CiselectId=$("#CiSelectId").val();
					var values=$("#NoValue").length;
					if(values == 0){
						$(CiselectId).append("<tr id='NoValue'><td align='center'><br><font color='#999999'>"+i18n.lable_notFindCi+"...</font></td></tr>");
					}
				}
			});
		},

		/**
		 * 获得字符串实际长度，中文2，英文1
		 * @param str 要获得长度的字符串
		 */
		getRelLength:function(str){
	        var realLength = 0, len = str.length, charCode = -1;
	        for (var i = 0; i < len; i++) {
	            charCode = str.charCodeAt(i);
	            if (charCode >= 0 && charCode <= 128) realLength += 1;
	            else realLength += 2;
	        }
	        return realLength;
		},
		 /** 
	     * js截取字符串，中英文都能用 
	     * @param str：需要截取的字符串 
	     * @param len: 需要截取的长度 
	     */
		cutstr:function(str, len) {
	        var str_length = 0;
	        var str_len = 0;
	        str_cut = new String();
	        str_len = str.length;
	        for (var i = 0; i < str_len; i++) {
	            a = str.charAt(i);
	            str_length++;
	            if (escape(a).length > 4) {
	                //中文字符的长度经编码之后大于4  
	                str_length++;
	            }
	            str_cut = str_cut.concat(a);
		        if (str_length > len+1) {
	                str_cut = str_cut.concat("...");
	                return str_cut;
	            }
	        }

	        
	        return str;
	        
	    },
	    /**
         * 状态格式化（拷贝自：common.knowledge.knowledgeGrid.statusFormatter）
         */
        statusFormatter:function(cell,event,data){
        	var _status={'1':i18n['knowledge_satus_normal'],'0':i18n['knowledge_satus_approving'],'-1':i18n['title_refused']};
        	return _status[cell];
        },
		/**
		 * 初始化
		 * @private
		 */
		init:function(){
		}
	}
}();